package cn.lblbc.todo

import android.app.Activity
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import java.text.SimpleDateFormat
import java.util.Locale

class TaskAdapter(
    private var tasks: List<Task>,
    private val activity: Activity? = null,
    private val onTaskClickListener: ((Task) -> Unit)? = null
) : RecyclerView.Adapter<TaskAdapter.TaskViewHolder>() {
    
    class TaskViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val titleTextView: TextView = itemView.findViewById(R.id.taskTitleText)
        val dueDateTextView: TextView = itemView.findViewById(R.id.taskDueDateText)
        val statusTextView: TextView = itemView.findViewById(R.id.taskStatusText)
    }
    
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TaskViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_task, parent, false)
        return TaskViewHolder(view)
    }
    
    override fun onBindViewHolder(holder: TaskViewHolder, position: Int) {
        val task = tasks[position]
        holder.titleTextView.text = task.title
        
        if (task.dueDate != null) {
            val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault())
            holder.dueDateTextView.text = dateFormat.format(task.dueDate)
        } else {
            holder.dueDateTextView.text = "未设置截止日期"
        }
        
        holder.statusTextView.text = if (task.isCompleted) "已完成" else "未完成"
        
        // 设置点击事件
        holder.itemView.setOnClickListener {
            onTaskClickListener?.invoke(task)
        }
    }
    
    override fun getItemCount(): Int = tasks.size
    
    fun updateTasks(newTasks: List<Task>) {
        tasks = newTasks
        notifyDataSetChanged()
    }
}